﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SimpleBlog.Models;
using SimpleBlog.Helpers;
using SimpleBlog.Infrastructure.Database;

namespace SimpleBlog.Infrastructure.Repositories
{
    public class TagRepository : Repository<Tag>, ITagRepository
    {
        public TagRepository(SbContext context) : base(context) { }

        public Dictionary<Tag, int> GetAllAndCount()
        {
            var dic = _Context.Tags
                .Select(x => new { Tag = x, Count = x.Posts.Count() })
                .ToDictionary(x => x.Tag, x => x.Count);
            return dic;
        }

        public Tag GetByEncodedName(string encodedName)
        {
            var tag = _Context.Tags.Include("Posts").SingleOrDefault(x => x.EncodedName.Equals(encodedName));
            return tag;
        }

        public void SetTags(Post post, IEnumerable<string> tags)
        {
            post.Tags.Clear();
            var tagsInDB = Search(x => tags.Contains(x.Name) || x.Posts.Any(y => y.PostId == post.PostId) || x.Posts.Count() == 0);

            foreach (var tagStr in tags)
            {
                var actualTag = tagsInDB.FirstOrDefault(x => x.Name == tagStr);
                if (actualTag != null)
                {
                    post.Tags.Add(actualTag);
                }
                else
                {
                    post.Tags.Add(new Tag() { Name = tagStr, EncodedName = EncoderHelper.EncodeTag(tagStr) });
                }
            }
            var toRemove = tagsInDB.Where(x => x.Posts.Count() == 0 || (x.Posts.Any(y => y.PostId == post.PostId) && !tags.Contains(x.Name))).ToList();
            toRemove.ForEach(x => _Context.Entry(x).State = System.Data.EntityState.Deleted);
        }
    }
}